package com.code.refactoring.zookeeper.book.chapter05.curatoe操作.分布式应用;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class Recipes_Barrier2 {
    //使用Curator实现分布式Barrier，是线程自动触发释放barrier

    static String barrier_path = "/curator_recipes_barrier_path";

    public static void main(String[] args) throws Exception {

        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        CuratorFramework client = CuratorFrameworkFactory.builder()
                                .connectString("localhost:2181")
                                .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
                        client.start();
                        DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client,
                                barrier_path, 5);
                        Thread.sleep(Math.round(Math.random() * 3000));
                        System.out.println(Thread.currentThread().getName() + "号进入barrier");
                        // 再enter这里阻塞，等待5个线程同时到齐，然后处理启动
                        barrier.enter();
                        System.out.println("启动...");
                        Thread.sleep(Math.round(Math.random() * 3000));
                        // 再leave这里等待5个线程一起，然后触发退出
                        barrier.leave();
                        System.out.println("退出...");
                    } catch (Exception e) {
                    }
                }
            }).start();
        }
    }
}